<?php
namespace Home\Controller;
use Lib\Controller\HomeBaseController;
use Home\Logic\WxBusinessAutorizerInfoLogic;
use Home\Service\GeohashService;
use Home\Logic\LocationLogic;
use Home\Service\DistanceService;

//个人中心-控制器
class PersonalController extends HomeBaseController {

    private $ordersModel;
	public  $userinfo; //微信用户信息

    public $orderStatus = array(
        '0' =>'未付款',
        '1' =>'已付款',
        '-1' =>'申请退款中',
        '-2' =>'退款审核中',
        '-3' =>'退款成功',
        '-4' =>'退款失败'
    );

	//构造方法
    public function __construct(){
        parent::__construct();
        $this->userinfo  = cookie('userinfo');
        //获取订单的model作为私有属性
        $this->ordersModel = D('Order');
    }

    /**
     * [my 个人中心页面]
     * @author xiezy
     * @date   2017-09-06
     * @return [type]     [description]
     */
    public function my(){
        //用户信息
        $userinfo = $this->userinfo;
        $userinfo['weixin_avatar'] = substr($userinfo['weixin_avatar'],0,strlen($userinfo['weixin_avatar'])-1);
        $userinfo['weixin_avatar'] = $userinfo['weixin_avatar'].'64';
        $userinfo['telphone']      = C('TELPHONE'); //客服电话

        $user              = M('user');
        $where['openid']   = $userinfo['openid'];
        $userData          = $user->where($where)->find();
        $userinfo['phone'] = $userData['phone']; //注册时绑定的电话号码

        $this->assign('info',$userinfo);
        $this->display();
    }

    /*********************** 我的訂單 ********************/
    /**
     * [order_list 我的订单页面]
     * @author xiezy
     * @date   2017-09-07
     * @return [type]     [默认--未付款]
     */
    public function order_list(){
        $userinfo = $this->userinfo;
    	$where['oi.openid']  = $userinfo['openid'];
    	//获取订单状态类型
    	$type = I('get.type');

    	if ($type == 'all') {
            //全部
        }else if($type == 'pay_success'){
            $where['o.status'] = array('neq',0); //1已付款 -1申请退款中 -2退款审核中 -3退款成功
        }else{
            $where['o.status'] = 0; // 0未付款
    	}
    	$group = 'o.ordersn';//分组条件
    	$order = 'o.id desc,o.wash_status asc';//排序条件
        $field = 'o.*,oi.*,uc.*,sa.address_name sa_address_name,sa.address_img sa_address_img,o.status o_status';    //查询字段
    	$orderList = $this->ordersModel->my_order_list($where,$field,$group,$order);
        foreach ($orderList as $key => $val) {
            if(isset($val['coupon_id'])){
                //獲取優惠券信息
                $couponPrice = D('coupon')->where('id = '.$val['coupon_id'])->find();
                $orderList[$key]['fact_price']   = sprintf("%.2f",$val['price'] - $couponPrice['price']);
            }else{
                $orderList[$key]['fact_price']   = sprintf("%.2f",$val['price']);
            }
        }
        $this->assign('list',$orderList);//分配变量
        $this->display(); //显示页面
    }

    /**
     * [application_refund 申請退款]
     * @author xiezy
     * @date   2017-10-09
     * @return [type]     [description]
     */
    public function application_refund(){
        //获取用户信息
        $userinfo = $this->userinfo;
        //1.獲取退款訂單號
        $ordersn = I('post.ordersnId');
        $reason  = I('post.reason');
        //2.處理该订单的状态为-退款审核中（-1）
        $order = M('order');
        $data['status']   = -1;
        $where['ordersn'] = $ordersn;
        $result = $order->where($where)->save($data);
        //3.添加退款订单
        $refund                      = M('refund');
        $save_data['ordersn']        = $ordersn;                    //订单号-商户支付
        $save_data['user_id']        = $userinfo['id'];             //用户id
        $save_data['submit_time']    = time();                      //微信退款-提交时间
        $save_data['refund_reason']  = !empty($reason) ? $reason :'退款';  //微信退款订单号
        $result_refund = $refund->data($save_data)->filter('strip_tags')->add();
        //4.成功提示
        if ($result && $result_refund) {
            $this->ajaxReturn(array('status'=>1,'info'=>'申請退款成功','url'=>'success'));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'申請退款失败','url'=>'fail'));
        }
    }


    /*********************** 我的訂單 ********************/


    /*********************** 意見建議 ********************/
    /**
     * [opinion 意见建议]
     * @author xiezy
     * @date   2017-09-07
     * @return [type]     [description]
     */
    public function opinion(){
        $this->display();
    }

    /**
     * [opinion 意见建议]
     * @author xiezy
     * @date   2017-09-07
     * @return [type]     [description]
     */
    public function add_opinion(){
        //1.获取用户信息
        $userinfo = $this->userinfo;
        //2.获取意见建议数据,并插入数据
        $save_data                   = I('post.');
        $UserSuggest                 = M('UserSuggest');
        $save_data['openid']         = $userinfo['openid'];       //用户openid
        // $save_data['openid']         = 1;       //用户openid
        $save_data['create_time']    = time();                    //创建时间
        $result_refund = $UserSuggest->data($save_data)->filter('strip_tags')->add();

        //3.成功提示
        if ($result_refund) {
            $this->ajaxReturn(array('status'=>1,'info'=>'您的意見已提交','url'=>'my'));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'意見提交失敗','url'=>'fail'));
        }
    }

    /************************ 意見建議 ********************/

    /************************ 我的爱车 ********************/
    /**
     * [mycar 读取个人中心-我的爱车]
     * @author xiezy
     * @date   2017-09-06
     * @return      [返回我的爱车页面]
     */
    public function mycar(){
    	// 当前登录者id
        $userinfo = $this->userinfo;
        $where['openid'] = $userinfo['openid'];
        $UserCar = M('UserCar');
        // 统计多少辆爱车
        $carcount = $UserCar->where($where)->count();
        // 我的爱车--信息
        $list = $UserCar->where($where)->order(array('default'=>'desc'))->select();
        $this->assign('user',$list);
        $this->assign('carcount',$carcount);
        $this->display();
    }

    /**
     * [gift_coupon 设为默认]
     * @author xiezy
     * @date   2017-09-06
     * @return [type]     [description]
     */
    public function setDefaultCar(){
    	// 获取需要处理的id
    	$id = I('post.id');
    	// 实例化-我的爱车
    	$UserCar = M('UserCar');
    	//1.把默认爱车取消默认状态
        $userinfo         = $this->userinfo;
    	$where['openid']  = $userinfo['openid']; //当前用户
    	$where['default'] = 1;
    	$data['default']  = 0;
    	$UserCar->where($where)->save($data);
    	//2.把当前爱车id设置为默认状态
    	$UserCar->find($id); // 查找主键为1的数据
		$UserCar->default = 1; // 修改数据对象
		$UserCar->save(); // 保存当前数据对象

    	// $setData['id'] = $id;
    	// $setData['default'] = 1;
    	// $UserCar->save($setData);
    	//3.成功提示
    	$this->ajaxReturn(array('status'=>1,'info'=>'设置成功','url'=>'mycar'));
    }

    /**
     * [gift_coupon 删除爱车]
     * @author xiezy
     * @date   2017-09-06
     * @return [type]     [description]
     */
    public function delLoveCar() {
    	//1.获取需要处理的id
    	$id = I('post.id');
    	//2.删除爱车
    	$UserCar = M('UserCar');
    	$UserCar->delete($id);
    	//3.成功提示
    	$this->ajaxReturn(array('status'=>1,'info'=>'刪除成功','url'=>'mycar'));
    }

    /**
     * 選擇車品牌
     */
    public function select_car_brand(){
        $result   = D('carBrand')->where('status = 1')->order('en_letter asc')->select();

        //返回页面
        $this->assign('list',$result);
        $this->display();
    }

    /**
     * [addmycarview 添加我的爱车页面]
     * @author xiezy
     * @date   2017-09-07
     * @return [type]     [页面]
     */
    public function addmycarview(){
        $this->display();
    }

    /**
     * [addMyCar 添加愛車]
     * @author xiezy
     * @date   2017-09-07
     */
    public function addMyCar(){
    	//需要新增的数据
        $userinfo           = $this->userinfo;
        $saveData           = I('post.');
        $saveData['openid'] = $userinfo['openid'];// 当前登录者id

        $UserCar            = M('userCar'); //  车辆信息
        $User               = M('user');    //  用户信息

        //判断 车牌号是否唯一
        if(!$this->checkLicenPlate($saveData)){
            // 当前登录者id
            $where['openid']    = $userinfo['openid'];
            $data = $UserCar->where($where)->find();

            //判断是否为用户的第一輛愛車，是则绑定默认爱车
            if (empty($data)) {
                $saveData['default'] = 1;// 默認當前愛車
            }

	        $UserCar->data($saveData)->filter('strip_tags')->add();

            //判断是否第一次注册，是则 绑定用户手机号码
            if ( !empty(I('post.phone')) ){
                $userData['phone']  = I('post.phone');   // 联系方式
                $User->where($where)->save($userData);
            }
            $this->ajaxReturn(array('status'=>1,'info'=>'添加成功','url'=>'mycar'));
        }else{
	        $this->ajaxReturn(array('status'=>0,'info'=>'添加失败,','url'=>'addmycarview'));
        }

    }

    /**
     * [checkLicenPlate 检查数据是否唯一]
     * @author xiezy
     * @date   2017-09-08
     * @return [boolen]     [true 不唯一，false 唯一车牌]
     */
    public function checkLicenPlate($dit){
    	//实例化操作对象
        $UserCar 				= M('UserCar');
        $where['openid']        = $dit['openid'];
        $where['license_plate'] = $dit['license_plate'];
        $data 					= $UserCar->where($where)->find();
    	if (!empty($data) ) {
    		return true;
    	}else{
    		return false;
    	}
    }
    /************************ 我的愛車 ********************/
    /**
     * 优惠券列表
     */
    public function coupon(){

        //用户使用的优惠卷
        $aWhere['member_id'] = array('eq',cookie('userinfo')['id'] );
        // $aWhere['member_id'] = array('eq','1');
        $applyCouponData = M('applyCoupon')->where($aWhere)->select();
        //用户拥有表该去掉的id
        $userCouponIDS = array();
        if (!empty($applyCouponData)) {
            foreach ($applyCouponData as $k => $v) {
                $userCouponIDS[] = $v['user_coupon_id'];
            }
            $uWhere['id'] = array('not in',$userCouponIDS);
        }
        //用户拥有的优惠卷
        $uWhere['member_id'] = array('in',array(-1,cookie('userinfo')['id']));
        // $uWhere['member_id'] = array('in',array(-1,1));
        $userCouponData = M('userCoupon')->where($uWhere)->select();

        //连上优惠卷信息
        foreach($userCouponData as $key =>$val){
            $checkCouponWhere['id'] = $val['coupon_id'];
            $checkCouponInfo = M('coupon')->where($checkCouponWhere)->find();
            if($checkCouponInfo['end_time'] < time()){
                unset($userCouponData[$key]);
            }else{
                $userCouponData[$key]['price'] = $checkCouponInfo['price'];
                $userCouponData[$key]['name']  = mb_strlen( $checkCouponInfo['name'])>5 ? mb_substr($checkCouponInfo['name'],0,4,'utf-8').'..': $checkCouponInfo['name'];
            }
        }
        $this->assign('coupon',$userCouponData);

        $this->display();
    }
}
